<?php namespace sacvoyage\storage;

require_once('Collection.php');

class Database  {


	public function __construct(Gateway $gateway, $name) {
		$this->_gateway=$gateway;
		$this->_name=$name;
		$this->_ensureTables();
	}

	public function getCollectionNames() {
		$name=$this->_gateway->escape($this->_name);
		$result=$this->_gateway->query(
			"SELECT name ".
			"FROM {$this->_prefix}collections "
		);
		$names=array();
		while($row=$result->fetch_assoc()) {
			$names[]=$row['name'];			
		}
		return $names;
	}

	public function &getCollection($collectionName) {
		if(!array_key_exists($collectionName, $this->_collectionCache)) {
			$this->_collectionCache[$collectionName]=new Collection(
				$this->_gateway, 
				$this->_prefix,
				$collectionName
			);
		}
		return $this->_collectionCache[$collectionName];
	}
	
	private $_gateway;
	private $_name;
	private $_prefix;
	private $_collectionCache=array();

	private function _ensureTables() {
		$escapedName=$this->_gateway->escape($this->_name);
		$result=$this->_gateway->query(
			"SELECT table_prefix FROM sacvoyage_databases ".
			"WHERE name='$escapedName' LIMIT 1"
		);
		if($row=$result->fetch_assoc()) {
			$this->_prefix=$row['table_prefix'];
		} else {
			$this->_prefix=$this->_gateway->generateTableName(
				'sacvoyage_'.$this->_name.'_collections', 
				'sacvoyage_', 
				'_collections'
			);
			$this->_prefix=substr($this->_prefix, 0, -11);
			
			$this->_gateway->query(
				"INSERT INTO sacvoyage_databases (name, table_prefix) ".
				"VALUES ('$escapedName', '{$this->_prefix}')"
			);
			
			$this->_gateway->query("CREATE TABLE {$this->_prefix}collections (
	name TINYTEXT NOT NULL,
	actual_table TINYTEXT NOT NULL,
	history_table TINYTEXT NOT NULL,
	UNIQUE(name(100)),
	UNIQUE(actual_table(100)),
	UNIQUE(history_table(100)),
	INDEX(name(100))
) DEFAULT CHARSET=utf8 COLLATE=utf8_bin");
		}
		
	}

}


?>
